package org.webdb.webapp.jackson;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.SerializerProvider;
import org.postgis.Polygon;

public class PolygonJSONSerializer {

    private PointComposedJSONSerializer pointComposedSerializer;

    public PolygonJSONSerializer(
            PointComposedJSONSerializer pointComposedSerializer) {
        this.pointComposedSerializer = pointComposedSerializer;
    }

    public void serialize(Polygon polygon, JsonGenerator jgen,
            SerializerProvider provider) throws JsonGenerationException,
            IOException {
        jgen.writeStartObject();
        jgen.writeStringField(GEOJSON.TYPE_ATTRIBUTE, GEOJSON.POLYGON_TYPE_NAME);
        jgen.writeFieldName(GEOJSON.COORDINATES_ATTRIBUTE);
        writePolygon(polygon, jgen);
        jgen.writeEndObject();
    }

    public void writePolygon(Polygon polygon, JsonGenerator jgen)
            throws JsonGenerationException, IOException {
        jgen.writeStartArray();
        for (int i = 0; i < polygon.numRings(); i++) {
            pointComposedSerializer
                    .writePointComposed(polygon.getRing(i), jgen);
        }
        jgen.writeEndArray();
    }
}
